const xlsx = require("xlsx");
export const fileExport = (txt, name="导出") => {
    let blob = new Blob([txt], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    let a = document.createElement("a");
    a.download = name
    a.style.display = 'none';
    let url = window.URL.createObjectURL(blob);
    a.href = url
    document.body.appendChild(a)
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url)
}

/**
 * 
 * @param {function} callback 回调 
 * @param {arr} filed 字段数组
 */
export const ImportExcel=(filed,callback)=>{
    let input=document.createElement("input");
    input.setAttribute("id","file");
    input.setAttribute("type", "file");
    input.style.display="none"
    input.setAttribute("accept", ".xlsx,.xls,.csv");
    input.addEventListener("change",function(e){
        ExcelTojson(e.target.files[0],filed,callback)
        document.body.removeChild(input)
        return 1
    })
    document.body.appendChild(input);
    input.click()
}

function ExcelTojson(file,filed,callback){
    if(!(file instanceof File)) throw new Error("请传入文件类型");
    let reader=new FileReader(file)
    reader.onload=function(){
        const buff=reader.result;
        const option={type:'array'};
        const book=xlsx.read(buff,option);
        const sheetName=book.SheetNames;
        const result= xlsx.utils.sheet_to_json(book.Sheets[sheetName[0]])
        let map=[]
        for (let obj of result) {
            let len = filed.length
            if (len <= 0) {
                break;
            }
            map.push(Object.entries(obj).reduce((acc, [k]) => {
                Object.defineProperty(acc, filed[filed.length- len],{value:obj[k], enumerable: true})
                len--
                return acc
            }, {}))
        }
        const cloneMap = JSON.parse(JSON.stringify(map))
        console.log('------', cloneMap)
        callback(cloneMap)
    }
    reader.readAsArrayBuffer(file)
}